/**
 * 
 */
package com.miolr.module.core.api;

import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.introspect.BasicBeanDescription;
import org.codehaus.jackson.map.ser.BeanPropertyWriter;
import org.codehaus.jackson.map.ser.BeanSerializerBuilder;
import org.codehaus.jackson.map.ser.BeanSerializerFactory;

/**
 * @author iday
 * 
 */
public class HibernateSerializerFactory extends BeanSerializerFactory {

	public final static HibernateSerializerFactory instance = new HibernateSerializerFactory(
			null);

	protected HibernateSerializerFactory(Config config) {
		super(config);
	}

	/* (non-Javadoc)
	 * @see org.codehaus.jackson.map.ser.BeanSerializerFactory#constructBeanSerializerBuilder(org.codehaus.jackson.map.introspect.BasicBeanDescription)
	 */
	@Override
	protected BeanSerializerBuilder constructBeanSerializerBuilder(
			BasicBeanDescription beanDesc) {
		return new HibernateBeanSerializerBuilder(beanDesc);
	}

	private static class HibernateBeanSerializerBuilder extends
			BeanSerializerBuilder {
		private final static BeanPropertyWriter[] NO_PROPERTIES = new BeanPropertyWriter[0];

		/**
		 * @param beanDesc
		 */
		public HibernateBeanSerializerBuilder(BasicBeanDescription beanDesc) {
			super(beanDesc);
		}

		/**
		 * @param src
		 */
		public HibernateBeanSerializerBuilder(BeanSerializerBuilder src) {
			super(src);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.codehaus.jackson.map.ser.BeanSerializerBuilder#build()
		 */
		@Override
		public JsonSerializer<?> build() {
			BeanPropertyWriter[] properties;
			// No properties or any getter? No real serializer; caller gets to
			// handle
			if (_properties == null || _properties.isEmpty()) {
				if (_anyGetter == null) {
					return null;
				}
				properties = NO_PROPERTIES;
			} else {
				properties = _properties
						.toArray(new BeanPropertyWriter[_properties.size()]);

			}
			return new HibernateBeanSerializer(_beanDesc.getType(), properties,
					_filteredProperties, _anyGetter, _filterId);
		}

	}

}
